﻿@page "/deviceconfig"
@using IotClientApp.Client.Pages.Dialog;
@using IotClientApp.Shared;
@using IotClientApp.Shared.Enums;
@using Newtonsoft.Json;
@inject HttpClient httpClient
@inject ISnackbar Snackbar
@inject IDialogService DialogService

<MudGrid>
<MudItem xs="12" md="2">
        <MudList Clickable="true" @bind-SelectedItem="selectedItem" @bind-SelectedValue="selectDeviceId">
            <MudListSubheader>
                设备
                <MudChip Color="Color.Secondary">
                    @(selectedItem?.Text ?? "You are dry") (@(selectDeviceId?.ToString() ?? "0"))
                </MudChip>
            </MudListSubheader>
            @foreach (var Device in Devices)
            {
                <MudListItem Text="@Device.Name" Value="@Device.Id" OnClick="async()=>{
await OpenConfig(Device.Id);
}" Icon="@Icons.Material.Filled.Drafts" />
            }
        </MudList>
 </MudItem>
 <MudItem xs="12" md="10">
        <MudButton Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.Save" IconColor="Color.Secondary" Size="Size.Large" OnClick="@(async() => {
await AddDeviceConfig();
})">新增</MudButton>
        <MudTable Items="@DeviceConfigs" Breakpoint="Breakpoint.Sm" LoadingProgressColor="Color.Info"
                  IsEditRowSwitchingBlocked="true" RowEditCommit="EditConfigItem" CanCancelEdit="true" MultiSelection="true" @bind-SelectedItems="selectedItems">
        <HeaderContent>
            <MudTh>名称</MudTh>
            <MudTh>描述</MudTh>
            <MudTh>值</MudTh>
            <MudTh>备注</MudTh>
        </HeaderContent>
        <RowTemplate>
                <MudTd DataLabel="Name">@context.Name</MudTd>
                <MudTd DataLabel="Desc">@context.Desc</MudTd>
                <MudTd DataLabel="Value">@context.Value</MudTd>
                <MudTd DataLabel="EnumInfo">@context.EnumInfo</MudTd>
            @*<MudTd>
                <MudButton Variant="Variant.Filled" OnClick="@(() => {
                    EditRow(context);
                })">编辑</MudButton>
                <MudButton Variant="Variant.Filled" OnClick="@(() => {
                    DelRow(context.Id);
                })">删除</MudButton>
            </MudTd>*@
        </RowTemplate>
        <RowEditingTemplate>
                <MudTd DataLabel="Name">
                    <MudTextField @bind-Value="@context.Name" Required />
                </MudTd>
                <MudTd DataLabel="Desc">
                    <MudTextField @bind-Value="@context.Desc" />
                </MudTd>
                <MudTd DataLabel="Value">
                    <MudNumericField @bind-Value="@context.Value" Required/>
                </MudTd>
                <MudTd DataLabel="EnumInfo">
                    <MudTextField @bind-Value="@context.EnumInfo" />
                </MudTd>
        </RowEditingTemplate>
        <PagerContent>
            <MudPagination SelectedChanged="PageChanged" Count="@pageCount" Class="pa-4" />
        </PagerContent>
            <EditButtonContent Context="button">
                <MudIconButton Size="@Size.Small" Icon="@Icons.Material.Outlined.Edit" Class="pa-0" OnClick="@button.ButtonAction" Disabled="@button.ButtonDisabled" />
            </EditButtonContent>
    </MudTable>
    </MudItem>
</MudGrid>

@code {
    Color _color = Color.Primary;
    private int pageCount;
    private int pageSize = 20;
    private int pageIndex = 1;
    private HashSet<DeviceConfigInfoModel> selectedItems = new HashSet<DeviceConfigInfoModel>();
    private List<DeviceInfoModel> Devices = new List<DeviceInfoModel>();
    private List<DeviceConfigInfoModel> DeviceConfigs = new List<DeviceConfigInfoModel>();
    private object selectDeviceId;
    MudListItem selectedItem;
    private string selectDeviceName = "";
    protected override async Task OnInitializedAsync()
    {
        await LoadDeviceData();
        if (Devices != null && Devices.Count() > 0)
        {
            await PageChanged(pageIndex);
        }
    }
    private async Task AddDeviceConfig()
    {
        var parameters = new DialogParameters<DeviceConfigSave_Dialog> { { x => x.DeviceConfigInfo, new DeviceConfigInfoModel {
            DeviceId = selectDeviceId.ToString() } }, { x => x.Title, "新增" } };
        var dialog = await DialogService.ShowAsync<DeviceConfigSave_Dialog>("新增", parameters);
        var result = await dialog.Result;
        if (!result.Canceled)
        {
            Console.WriteLine("ok");
            await LoadDeviceConfigData(pageIndex);
        }
    }
    private async void EditConfigItem(object element)
    {
        var config = (DeviceConfigInfoModel)element;
        Console.WriteLine(config.Name);
        var response = await httpClient.PostAsJsonAsync("api/DeviceConfig/SaveDeviceConfigInfo", new DeviceConfigInfoModel
            {
                Id = config.Id,
                Name = config.Name,
                DeviceId = selectDeviceId.ToString(),
                Desc = config.Desc,
                EnumInfo = config.EnumInfo,
                Value = config.Value
            });
        try
        {
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ApiResult<string>>(responseContent);

                if (result != null && result.Code == ResultCode.Success)
                {
                    Snackbar.Add("成功", Severity.Success);
                    await LoadDeviceConfigData(pageIndex);
                }
                else if (result != null && result.Code != ResultCode.Success)
                {
                    Snackbar.Add(result.ErrorMsg, Severity.Error);
                }
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add(ex.Message, Severity.Error);
            Console.WriteLine(ex.Message);
        }
    }
    private void DelRow(int id)
    {

    }
    private void EditRow(DeviceConfigInfoModel deviceConfigInfo)
    {

    }
    private async Task OpenConfig(string deviceId)
    {
        pageIndex = 1;
        await LoadDeviceConfigData(pageIndex);
    }
    private async Task PageChanged(int i)
    {
        await LoadDeviceConfigData(i - 1);
    }
    private async Task LoadDeviceConfigData(int pageIndex)
    {
        DeviceConfigs.Clear();
        this.pageIndex = pageIndex;
        var response = await httpClient.PostAsJsonAsync("api/DeviceConfig/GetDeviceConfigInfos", new GetDeviceConfigInfoModel
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                DeviceId = selectDeviceId?.ToString()
            });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceConfigInfoModel>>(responseContent);

                if (result != null)
                {
                    DeviceConfigs = result.Data;
                    pageCount = result.PageCount;
                }
                StateHasChanged();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    private async Task LoadDeviceData()
    {
        var response = await httpClient.PostAsJsonAsync("api/Device/GetDeviceInfos", new GetDeviceInfoModel
        {
        });
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();

            Console.WriteLine(responseContent);
            try
            {
                var result = JsonConvert.DeserializeObject<PageResponse<DeviceInfoModel>>(responseContent);
                if (result != null)
                {
                    if (result.Data.Count() > 0)
                    {
                        selectDeviceId = result.Data.First().Id;
                        selectDeviceName = result.Data.First().Name;
                        Console.WriteLine(selectDeviceName);
                    }
                    Devices = result.Data;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
